package com.cwd.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.cwd.constant.RedisConstant;
import com.cwd.dao.SetmealDao;
import com.cwd.entity.PageResult;
import com.cwd.entity.QueryPageBean;
import com.cwd.pojo.Setmeal;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: com.cwd.service
 * @ClassName: SetmealServiceImpl
 * @Author: CWD
 * @Date: 2020/3/4 12:41
 * @Description:
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;
    //新增检查套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加检查套餐信息
        setmealDao.add(setmeal);
        //添加检查套餐和检查组的关联
        Integer setmealId = setmeal.getId();
        setReferCheckgroupWithSetmeal(setmealId,checkgroupIds);

        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //在添加套餐之后需要重新生成静态页面（套餐列表页面，套餐详情页面）
        generateMobileStaticHtml();
    }
    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }
    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);  //键名称必须和模板中的对应
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（有多个套餐，所以每个套餐详情都得有一个页面）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));  //键名称必须和模板中的对应
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        //第一个参数是模板页面的名称，第二个参数是生成之后的页面的名称，第三个参数是生成页面所需的参数

        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页插件，会在执行sql之前将分页关键字追加到sql语句之后
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> setmealList = page.getResult();
        return new PageResult(total,setmealList);
    }
    //查询所有
    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> list = setmealDao.findAll();
        return list;
    }
    //根据id查询套餐信息（套餐基本信息，对应的检查组以及检查组对应的检查项）
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }
    //获取套餐名称和预约数量，用于前台echarts百分比图表展示
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        List<Map<String,Object>> list = setmealDao.findSetmealCount();
        return list;
    }

    //设置检查组和套餐的关联
    public void setReferCheckgroupWithSetmeal(Integer setmealId,Integer[] checkgroupIds){
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.addRefer(map);
            }
        }
    }
}
